package com.wwinsoft.framework.web.system;

import java.util.List;

import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.wwinsoft.framework.entity.system.Code;
import com.wwinsoft.framework.entity.system.CodeType;
import com.wwinsoft.framework.service.ServiceException;
import com.wwinsoft.framework.service.system.CodeManager;
import com.wwinsoft.framework.web.CrudActionSupport;
import com.wwinsoft.modules.orm.Page;
import com.wwinsoft.modules.orm.PropertyFilter;
import com.wwinsoft.modules.utils.web.struts2.Struts2Utils;

/**
 * @author: Tim.Chen
 * @since: 1.0
 */
@Namespace("/system")

@Results({ @Result(name = CrudActionSupport.RELOAD, location = "code.action", type = "redirect") })
public class CodeAction extends CrudActionSupport<Code> {

    private Long id;
    private Code entity;
    private Page<Code> page = new Page<Code>();
    private List<CodeType> codeTypeList;

    @Autowired
    private CodeManager codeManager;

    public void setId(Long id) {
        this.id = id;
    }

    public Page<Code> getPage() {
        return page;
    }

    public List<CodeType> getCodeTypeList() {
        return codeTypeList = codeManager.getMaintainedCodeTypeList();
    }

    @Override
    public void prepareModel() throws Exception {
        if (id == null) {
            entity = new Code();
        } else {
            entity = codeManager.getCode(id);
        }
    }

    @Override
    public Code getModel() {
        return entity;
    }

    @Override
    public String list() throws Exception {
        List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(Struts2Utils.getRequest());
        //设置默认排序方式
        if (!page.isOrderBySetted()) {
            page.setOrderBy("id");
            page.setOrder(Page.ASC);
        }
        page = codeManager.searchCode(page, filters);
        return SUCCESS;
    }

    @Override
    public String input() throws Exception {
        return INPUT;
    }

    public String view() throws Exception {
        prepareModel();
        return "view";
    }

    @Override
    public String save() throws Exception {
        codeManager.saveCode(entity);
        addActionMessage("保存代码成功");
        return RELOAD;
    }

    @Override
    public String delete() throws Exception {
        try {
            codeManager.deleteCode(id);
            addActionMessage("删除代码成功");
        } catch (ServiceException e) {
            logger.error(e.getMessage(), e);
            addActionError(e.getMessage());
        }
        return RELOAD;
    }
}